package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     *营业额统计
     * @param begintime
     * @param endtime
     * @return
     */

    public TurnoverReportVO getTurnOverStatistics(LocalDate begintime, LocalDate endtime) {
        //根据开始结束时间 将每天的天数存放在集合里面
        //也就是第一个传参数
        List<LocalDate> list = new ArrayList<>();

        while (!begintime.equals(endtime)) {
            begintime = begintime.plusDays(1);
            list.add(begintime);
        }
       // list.add(end);
        String dateList = StringUtils.join(list, ",");
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setDateList(dateList);
        //存放每天营业额
        List<Double> turnoverlist=new ArrayList<>();
        //获取每天营业额 查询每天的对应的营业额数据
        for (LocalDate localDate : list) {
            //一天开始结束时间 （需要知道三个条件 1.一天开始 2 结束 3.状态（是已完成））
            LocalDateTime begin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(localDate, LocalTime.MAX);

            //select sum(count) from orders where order_time>?and order_time<? and status=5
            Map map=new HashMap();
            map.put("begin",begin);
            map.put("end",end);
            map.put("status", Orders.COMPLETED);
          //查出一天的营业额 存放在集合里面
          Double turnover= orderMapper.getsum(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverlist.add(turnover);
        }

        String turnoverList = StringUtils.join(turnoverlist, ",");
        turnoverReportVO.setTurnoverList(turnoverList);

        return turnoverReportVO;
    }

    /**
     * 用户数量统计
     * @param begintime
     * @param endtime
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begintime, LocalDate endtime) {
     //dateList 存放日期
        List<LocalDate> list1=new ArrayList<>();

        while (!begintime.equals(endtime)){
            begintime=begintime.plusDays(1);
            list1.add(begintime);
        }
        String dateList = StringUtils.join(list1, ",");
       UserReportVO userReportVO=new UserReportVO();
        userReportVO.setDateList(dateList);


        //存放每天的新增用户数量 select count(id) from user where order_time>? and order_time<?
        List<Integer> list2=new ArrayList<>();
        //存放每天的总用户数量 select count(id) from user where order_time< order_time
        List<Integer> list3=new ArrayList<>();
        for (LocalDate localDate : list1) {
            LocalDateTime begin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map=new HashMap();
            map.put("end",end);
            Integer totaluser = userMapper.CreatByMap(map);
            map.put("begin",begin);
            Integer newuser = userMapper.CreatByMap(map);
            list2.add(newuser);
            list3.add(totaluser);
        }
        String newUserList = StringUtils.join(list2, ",");
        String totalUserList = StringUtils.join(list3, ",");

        userReportVO.setNewUserList(newUserList);
        userReportVO.setTotalUserList(totalUserList);
        return userReportVO;
    }
    /**
     * 订单数量统计
     * @param begintime
     * @param endtime
     * @return
     */

    public OrderReportVO getOrdersStatistics(LocalDate begintime, LocalDate endtime) {
        //dateList 存放日期
        List<LocalDate> list1=new ArrayList<>();

        while (!begintime.equals(endtime)){
            begintime=begintime.plusDays(1);
            list1.add(begintime);
        }

        //存放每日订单数，以逗号分隔，例如：260,210,215
           List<Integer> list2=new ArrayList<>();
        //每日有效订单数，以逗号分隔，例如：20,21,10
        List<Integer> list3=new ArrayList<>();
        //订单总数
       Integer totalOrderCount=0;
        //有效订单数
       Integer validOrderCount=0;
        //订单完成率
        Double orderCompletionRate=0.0;
        for (LocalDate localDate : list1) {
            LocalDateTime begin = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询每天订单数量 select count(id) from orders where oreder_time>? and order_time<?
            Integer orderCount1 = getOrderCount(begin, end, null);
          list2.add(orderCount1);
          totalOrderCount=totalOrderCount+orderCount1;
            //查询每天订单有效数量 select count(id) frome orders where order_time>? and order_time<? and status=?
            Integer orderCount2 = getOrderCount(begin, end, Orders.COMPLETED);
            validOrderCount=validOrderCount+orderCount2;
           list3.add(orderCount2);
        }
        //计算完成率
        if (totalOrderCount!=0){
            orderCompletionRate= validOrderCount.doubleValue()/totalOrderCount;
        }
        OrderReportVO orderReportVO=new OrderReportVO();
        String dateList = StringUtils.join(list1, ",");
        String  orderCountList= StringUtils.join(list2, ",");
        String validOrderCountList = StringUtils.join(list3, ",");

        orderReportVO.setDateList(dateList);
        orderReportVO.setOrderCountList(orderCountList);
        orderReportVO.setValidOrderCountList(validOrderCountList);
        orderReportVO.setTotalOrderCount(totalOrderCount);
        orderReportVO.setValidOrderCount(validOrderCount);
        orderReportVO.setOrderCompletionRate(orderCompletionRate);

    return orderReportVO;
    }

    /**
     * 得到每天的订单数
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end,Integer status){
        Map map=new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status",status);


      return   orderMapper.createByMap(map);
    }

    /**
     * 销量top10
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> saleTop10 = orderMapper.getSaleTop10(beginTime, endTime);
        List<String> names = saleTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");

        List<Integer> numbers = saleTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO.builder().nameList(nameList).numberList(numberList).build();
    }


    /**
     * 导出运营数据报表
     * @param response
     */
    public void exportBusinssDate(HttpServletResponse response) {
        //1. 查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        //2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板文件创建一个新的Excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    }

